<template>
  <div class="container">
    <a-card class="general-card" title="查询条件">
      <a-row>
        <a-col :flex="1">
          <a-form :model="searchModel" layout="inline" label-align="right">
            <a-row>
              <a-col flex="auto">
                <a-form-item field="username" label="账号">
                  <a-input
                    v-model="searchModel.username"
                    placeholder="请输入账号"
                  />
                </a-form-item>
              </a-col>
              <a-col flex="auto">
                <a-form-item field="phone" label="手机号">
                  <a-input
                    v-model="searchModel.phone"
                    placeholder="请输入手机号"
                  />
                </a-form-item>
              </a-col>
              <a-col flex="auto">
                <a-form-item field="status" label="是否锁定">
                  <a-select
                    v-model="searchModel.status"
                    :options="statusOptions"
                    placeholder="全部"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 86px" direction="vertical" />
        <a-col :flex="'86px'" style="text-align: right">
          <a-space direction="vertical" :size="18">
            <a-button type="primary" @click="refresh">
              <template #icon>
                <icon-search />
              </template>
              查询
            </a-button>
            <a-button @click="reset">
              <template #icon>
                <icon-refresh />
              </template>
              重置
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />
      <a-row style="margin-bottom: 16px">
        <a-col :span="16">
          <a-space>
            <a-button
              v-permission="authority.SYS_USER_ADD"
              type="primary"
              @click="add"
            >
              <template #icon>
                <icon-plus />
              </template>
              新建
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-table
        row-key="id"
        :loading="loading"
        :pagination="pagination"
        :data="renderData"
        :columns="columns"
        :bordered="{ wrapper: true, cell: true }"
        @page-change="changeCurrent"
        @page-size-change="changePageSize"
      >
        <template #role="{ record }">
          {{ getRoleNames(record.roleIds) }}
        </template>
        <template #status="{ record }">
          <span v-if="record.status === '1'" style="color: red">是</span>
          <span v-else style="color: lightgreen">否</span>
        </template>
        <template #operations="{ record }">
          <a-button
            v-permission="authority.SYS_USER_EDIT"
            type="text"
            size="small"
            @click="edit(record)"
          >
            <template #icon>
              <icon-edit />
            </template>
            编辑
          </a-button>
          <a-button
            v-permission="authority.SYS_USER_PASSWORD"
            type="text"
            size="small"
            @click="password(record)"
          >
            <template #icon>
              <icon-tool />
            </template>
            修改密码
          </a-button>
          <a-popconfirm
            :content="`此操作将永久删除该用户(${record.username}), 是否继续?`"
            type="warning"
            @ok="del(record.id)"
          >
            <a-button
              v-permission="authority.SYS_USER_DEL"
              type="text"
              size="small"
              status="danger"
            >
              <template #icon>
                <icon-delete />
              </template>
              删除
            </a-button>
          </a-popconfirm>
        </template>
      </a-table>
    </a-card>
    <UserForm
      v-model:visible="formDialogVisible"
      :form-data="formData"
      @refresh="refresh"
    />
    <div>
      <a-modal
        v-model:visible="pwdModalVisible"
        :title="pwdTitle"
        :footer="false"
        width="400px"
      >
        <a-form :model="pwdForm" @submit="changePassword">
          <a-form-item
            field="password"
            label="密码"
            :rules="[
              { required: true, message: '密码不能为空' },
              { minLength: 8, message: '密码长度至少为8位' },
            ]"
          >
            <a-input v-model="pwdForm.password" />
          </a-form-item>

          <a-form-item>
            <a-button html-type="submit" type="primary">确定</a-button>
          </a-form-item>
        </a-form>
      </a-modal>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, computed } from 'vue';
  import { getUserPage, delUser, changePwd } from '@/api/upms/user';
  import { Message } from '@arco-design/web-vue';
  import { getRoleList } from '@/api/upms/role';
  import authority from '@/utils/authority';
  import { usePagination, useRequest } from 'vue-request';
  import defaultPageOptions from '@/utils/pagination';
  import UserForm from './components/user-form.vue';

  // 初始数据
  const generateModel = () => {
    return {
      username: undefined,
      phone: undefined,
      status: undefined,
    };
  };

  const pwdForm = ref({
    id: '',
    password: '',
  });

  const pwdTitle = ref('修改密码');

  const searchModel = ref(generateModel());
  const formData = ref();

  const statusOptions = [
    {
      label: '是',
      value: '1',
    },
    {
      label: '否',
      value: '0',
    },
  ];

  const columns = [
    { title: 'ID', dataIndex: 'id' },
    { title: '账号', dataIndex: 'username' },
    { title: '所属机构', dataIndex: 'orgName' },
    { title: '角色', slotName: 'role' },
    { title: '手机号', dataIndex: 'phone' },
    { title: '创建时间', dataIndex: 'createTime' },
    { title: '是否锁定', slotName: 'status' },
    { title: '操作', slotName: 'operations' },
  ];

  const {
    data,
    loading,
    refresh,
    changeCurrent,
    changePageSize,
    current,
    pageSize,
    total,
  } = usePagination(
    (params) => getUserPage({ ...params, ...searchModel.value }),
    {
      ...defaultPageOptions,
    }
  );

  const renderData = computed(() => data.value?.records || []);

  const pagination = computed(() => ({
    current: current.value,
    pageSize: pageSize.value,
    showTotal: true,
    showPageSize: true,
    total: total.value,
  }));

  // 弹出框标记
  const formDialogVisible = ref(false);

  const pwdModalVisible = ref(false);

  const reset = () => {
    searchModel.value = generateModel();
  };
  const add = () => {
    formDialogVisible.value = true;
    formData.value = {};
  };
  const edit = (e: any) => {
    formDialogVisible.value = true;
    formData.value = { ...e };
  };
  const del = async (id: string) => {
    await delUser(id).then(() => {
      Message.success('删除成功');
      refresh();
    });
  };

  const password = (e: any) => {
    pwdTitle.value = `修改用户${e.username}的密码`;
    pwdForm.value.id = e.id;
    pwdModalVisible.value = true;
  };

  const changePassword = async ({
    values,
    errors,
  }: {
    values: any;
    errors: any;
  }) => {
    if (!errors) {
      changePwd(values.id, values.password).then(() => {
        Message.success('修改成功');
        pwdModalVisible.value = false;
      });
    }
  };
  const { data: roles } = useRequest(getRoleList);

  const getRoleNames = (roleIds: []) =>
    roleIds
      ?.map(
        (id: any) =>
          roles.value?.find((r: { id: any }) => r.id === id)?.roleName ?? ''
      )
      ?.join(' , ');
</script>

<script lang="ts">
  export default {
    name: 'User',
  };
</script>

<style scoped lang="less">
  .container {
    padding: 0px 10px 0px 10px;
  }
</style>
